package com.free.semantic.web.controller;

import com.free.semantic.common.BaseNode;
import com.free.semantic.common.LocatorNode;
import com.free.semantic.common.ParamNode;
import com.free.semantic.core.common.UserConceptManageInfo;
import com.free.semantic.core.conceptservice.ConceptService;
import com.free.semantic.core.service.ConceptGroupManage;
import com.free.semantic.web.annotation.RequireAuth;
import com.free.semantic.web.configure.ControllerConfig;
import com.free.semantic.web.req.TaskPathRequest;
import com.free.semantic.web.result.Result;
import com.free.semantic.web.security.JwtUtil;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@CrossOrigin(methods = {RequestMethod.GET, RequestMethod.POST, RequestMethod.OPTIONS})
@RestController
@ControllerConfig
@RequestMapping("/controller")
public class FinalController {

    @Resource
    private ConceptGroupManage groupManage;

    @Resource
    private ConceptService conceptService;

    private Map<Long, UserConceptManageInfo> buffer = new HashMap<>();

    @PostMapping(value = {"/{conceptName}/semantic", "/semantic"})
    public Result<List<Object>> postTake(@PathVariable(name = "conceptName", required = false) String conceptName,
                                         @RequestBody TaskPathRequest taskPathRequest) {
        List<Object> value = groupManage.getManage(conceptName).goByLocatorNode(convert(taskPathRequest.getFrom()),
                taskPathRequest.getDestRangeObj());
        return Result.success(value);
    }

    private List<BaseNode> convert(List<ParamNode> paramNodes) {
        List<BaseNode> result = new ArrayList<>();
        for (int i = 0; i < paramNodes.size(); i++) {
            ParamNode paramNode = paramNodes.get(i);
            if (paramNode.getValue() == null && i != 0) {
                result.add(new LocatorNode(paramNode.getNodeName()));
            } else {
                result.add(paramNode);
            }
        }
        return result;
    }

    private Long getCurrentUserId() {
        return JwtUtil.getCurrentUserId();
    }

    @RequireAuth
    @PostMapping(value = {"user/{conceptName}/semantic", "user/semantic"})
    public Result<List<Object>> userPostTake(@PathVariable(name = "conceptName", required = false) String conceptName,
                                             @RequestBody TaskPathRequest taskPathRequest) {
        Long currentUserId = getCurrentUserId();
        buffer.putIfAbsent(currentUserId, conceptService.loadUserConcepts(currentUserId));
        List<Object> value = buffer.get(currentUserId).getManage(conceptName).goByLocatorNode(convert(taskPathRequest.getFrom()),
                taskPathRequest.getDestRangeObj());
        return Result.success(value);
    }

}
